const express = require('express');
const cors = require('cors');
const { v4: uuidv4 } = require('uuid');
const app = express();

// 中间件
app.use(cors());
app.use(express.json());

// 内存存储任务数据
let tasks = [
  {
    id: '1',
    title: '完成Render部署教程',
    description: '编写一个完整的Render部署示例',
    completed: false,
    createdAt: new Date().toISOString()
  }
];

// 健康检查路由
app.get('/health', (req, res) => {
  res.status(200).json({ status: 'ok', timestamp: new Date().toISOString() });
});

// 获取所有任务
app.get('/tasks', (req, res) => {
  res.json(tasks);
});

// 获取单个任务
app.get('/tasks/:id', (req, res) => {
  const task = tasks.find(t => t.id === req.params.id);
  if (!task) {
    return res.status(404).json({ message: '任务不存在' });
  }
  res.json(task);
});

// 创建新任务
app.post('/tasks', (req, res) => {
  if (!req.body.title) {
    return res.status(400).json({ message: '任务标题不能为空' });
  }

  const newTask = {
    id: uuidv4(),
    title: req.body.title,
    description: req.body.description || '',
    completed: false,
    createdAt: new Date().toISOString()
  };

  tasks.push(newTask);
  res.status(201).json(newTask);
});

// 更新任务
app.put('/tasks/:id', (req, res) => {
  const taskIndex = tasks.findIndex(t => t.id === req.params.id);
  if (taskIndex === -1) {
    return res.status(404).json({ message: '任务不存在' });
  }

  if (!req.body.title && req.body.completed === undefined) {
    return res.status(400).json({ message: '至少需要提供标题或完成状态' });
  }

  const updatedTask = {
    ...tasks[taskIndex],
    title: req.body.title || tasks[taskIndex].title,
    description: req.body.description !== undefined ? req.body.description : tasks[taskIndex].description,
    completed: req.body.completed !== undefined ? req.body.completed : tasks[taskIndex].completed
  };

  tasks[taskIndex] = updatedTask;
  res.json(updatedTask);
});

// 删除任务
app.delete('/tasks/:id', (req, res) => {
  const initialLength = tasks.length;
  tasks = tasks.filter(t => t.id !== req.params.id);

  if (tasks.length === initialLength) {
    return res.status(404).json({ message: '任务不存在' });
  }

  res.json({ message: '任务已删除' });
});

// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
});
    